from flask import request
import urllib.request
import json


def planning(origin, destination):
    key = '78019793b012a9c6b8e361aa55f9282c'
    url = 'https://restapi.amap.com/v5/direction/walking?key='
    url += key + '&origin=' + origin + '&destination=' + destination + '&isindoor=0&show_fields=cost,polyline'
    # print(url)
    response = urllib.request.urlopen(url).read()
    res_dic = json.loads(response)
    # print(res_dic)
    status = res_dic['status']
    if status != '1':
        return False

    paths = res_dic['route']['paths']
    total_distance = 0
    pts_li_temp = []
    for path in paths:
        total_distance += int(path['distance'])
        steps = path['steps']
        for step in steps:  # step : 'xxx.xxx,xxx.xxx;xxx.xxx,xxx.xxx;...'
            pts_li_temp.extend(step['polyline'].split(';'))
    pts = list(set(pts_li_temp))  # 去重
    pts.sort(key=pts_li_temp.index)
    # print(pts)
    pts_2 = []
    for pt in pts:
        temp_list = pt.split(',')
        temp_list[0] = float(temp_list[0])
        temp_list[1] = float(temp_list[1])
        pts_2.append(temp_list)  # 二维列表
    return pts_2


def loc_str(code):
    key = ''
    with open(file='controller/key.txt', mode='r', encoding='utf-8') as fb:
        key = fb.readline()
    url = 'https://restapi.amap.com/v3/geocode/regeo?key='
    url += key + '&location=' + code
    response = urllib.request.urlopen(url).read()
    res_dic = json.loads(response)
    status = res_dic['status']
    if status == 0:
        return -1
    print(res_dic)
    # res_dic['regeocode']['addressComponent']['streetNumber']['number']
    regeocode = res_dic['regeocode']
    addressComponent = regeocode['addressComponent']
    province = addressComponent['province']  # 省
    city = addressComponent['city']  # 市(若是直辖市，此处为空列表)
    if city is []:
        city = None
    township = addressComponent['township']  # 镇
    district = addressComponent['district']  # 区/县
    street = addressComponent['streetNumber']['street']  # 街道
    number = addressComponent['streetNumber']['number']
    street += number
    addr_str = regeocode['formatted_address'] + number
    resp_dic = {'pro': province, 'city': city, 'township': township, 'dist': district, 'street': street}
    return addr_str


if __name__ == '__main__':
    origin = '116.397244,39.90788'
    destination = '116.40675,39.909337'
    res = planning(origin, destination)
    if res is not False:
        print(res)
    else:
        print('error')